
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- 上述3个meta标签*必须*放在最前面，任何其他内容都*必须*跟随其后！ -->
  <meta name="description" content="xms">
  <meta name="author" content="Xms">
  <link rel="icon" href="/content/favicon.ico">

  <title>系统 - 安全 - 权限资源管理</title>

  <!-- Bootstrap core CSS -->
  <link href="/content/css/bootstrap3.3.5/bootstrap.min.css" rel="stylesheet">

  <!-- Custom styles for this template -->
  <link href="/content/css/font-awesome.min.css" rel="stylesheet">
  <link href="/content/css/common.css" rel="stylesheet">
  <link href="/content/js/jquery-toast/jquery.toast.min.css" rel="stylesheet">
  <link id="themeLink" href="/content/css/theme/default.css" rel="stylesheet" />
  <!-- Bootstrap core JavaScript ================================================== -->
  <!-- Placed at the end of the document so the pages load faster -->
  <script src="/content/js/jquery.min.js"></script>
  <script src="/content/js/bootstrap.min.js"></script>
  <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
  <script src="/content/js/ie10-viewport-bug-workaround.js"></script>
  <script src="/content/js/jquery.bootstrap.min.js"></script>
  <script src="/content/js/json2.js"></script>
  <script src="/content/js/xms.utility.js"></script>
  <script src="/content/js/jquery-ui-1.10.3/ui/jquery.ui.core.js"></script>
  <script src="/content/js/jquery-ui-1.10.3/ui/jquery.ui.widget.js"></script>
  <script src="/content/js/jquery-ui-1.10.3/ui/jquery.ui.mouse.js"></script>
  <script src="/content/js/jquery-ui-1.10.3/ui/jquery.ui.draggable.js"></script>
  <script src="/content/js/jquery-toast/jquery.toast.min.js"></script>
  <script src="/content/js/xms.jquery.js"></script>
  <script src="/content/js/xms.web.js"></script>
  <script src="/content/js/commonlabels.js"></script>
  <script src="/content/js/common/pagecontext.js"></script>
  <script src="/api/user/usercontext"></script>
  <script>
  jQuery(function () {
    Xms.Web.Loading();
    if (typeof parent !== 'undefined') {
      if (parent != window) {//判断当前页面是否为子页面
        $('body').addClass('xms-subpage');
      }
    }
  });
  function changeTheme(body,themename) {
    $("#themeLink").attr('href', '/content/css/theme/' + themename+'.css');
  }
</script>
  <link href="/content/css/jqtree.css" rel="stylesheet">
  <style>
    body {
      padding-top: 0;
    }
  </style>
</head>

<body data-spy="scroll" data-target="#myScrollspy">
<div class="container-fluid" id="body">
  <div class="row">
    <div class="shadeBox" style="background-color:#000000; opacity:0.5;width:100%;position:absolute;z-index:10;display:none;"></div>
    <div class="col-md-12" id="main" style="margin-bottom:80px;">
      <div><br class="breadcrumb" /></div>
      <div id="content"></div>
      <div class="page-render-wrap">
        <!--main-->

        <div class="container-fluid">
          <div class="row">
            <div class="col-sm-4">
              <div class="panel panel-default">
                <div class="panel-heading">
                  <h3 class="panel-title">
                    <a data-toggle="collapse"
                       href="#collapseOne">
                      <strong id="name"></strong> - <strong>权限控制启用状态</strong>
                    </a>
                  </h3>
                </div>
                <div id="collapseOne" class="panel-collapse collapse in">
                  <div class="panel-body">
                    <form id="editform" class="form-horizontal text-center"
                          data-jsonajax="true" data-istip="true" method="post">
                      <input id="resourcename" name="resourcename" type="hidden" />
                      <input id="typecode" name="typecode" type="hidden" />
                      <div class="btn-group">
                        <button class="btn btn-default" type="button" data-toggle="button" id="toggleChecked" data-state="1">
                          <span class="glyphicon glyphicon-check"></span> 全选 / <span class="glyphicon glyphicon-unchecked"></span> 取消
                        </button>
                        <button class="btn btn-primary" type="submit"><span class="glyphicon glyphicon-saved"></span> 保存</button>
                      </div>
                      <hr />
                      <div class="">
                        <div class="input-group"><input class="form-control" id="tree_searcher" /><span class="input-group-addon"><em class="glyphicon glyphicon-search"></em></span></div>
                      </div>
                      <div id="resource_tree" class="text-left" data-url="" style="min-height:400px;max-height:400px; overflow:auto; padding:0 5px;">
                      </div>
                    </form>
                  </div>
                </div>
              </div>
            </div>

            <div class="col-sm-8">
              <table class="table table-hover table-bordered  table-striped table-condensed">
                <thead>
                <tr>
                  <th>名称</th>
                  <th width="30%">操作</th>
                </tr>
                </thead>
                <tbody data-bind="foreach: lines">
                <tr>
                  <td>
                    <a href="#" data-bind="click: $root.click"><span data-bind="text: modulelocalizedname"></span></a>
                  </td>
                  <td>
                    <a class="btn btn-info btn-xs" data-bind="click: $root.click"><span class="glyphicon glyphicon-cog"></span></a>
                  </td>
                </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>

      </div>
      <nav class="navbar navbar-default navbar-fixed-bottom hide" role="navigation" id="body-footer">
        <div class="container">
          <div class="navbar-form navbar-right" id="body-footer-content">
          </div>
        </div>
      </nav>
    </div>
  </div>
</div>

<script src="/content/js/xms.utility.js"></script>
<script src="/content/js/jquery.form.js"></script>
<script src="/content/js/jquery-validate/jquery.validate.min.js"></script>
<script src="/content/js/xms.web.js"></script>
<script src="/content/js/xms.jquery.js"></script>
<script src="/content/js/tree.jquery.js"></script>
<script src="/content/js/knockout-2.2.0.js"></script>
<script>
  var model = $.urlParamObj(location.href);
  var $tree = $('#resource_tree'), $editform = $("#editform");
  $(function () {
    Xms.Web.Form($editform, function (response) {
      $('input[value^="parentid_"]').prop('disabled', false);
      //  Xms.Web.Toast(response.Content,response.IsSuccess);
    }, null, function () {
      $('input[value^="parentid_"]').prop('disabled', true)
    });
    $("#toggleChecked").click(function () {
      var state = $(this).attr("data-state");
      if (state == 1) {
        $tree.find("input[type=checkbox]").prop("checked", true);
        $(this).attr("data-state", 0).removeClass("active");
      } else {
        $tree.find("input[type=checkbox]").prop("checked", false);
        $(this).attr("data-state", 1).addClass("active");
      }
    });
    getResourceInfo(function(data){
      var currentSource = $.grep(data, function (n, i) {
        return n.modulename == model.resourcename;
      })[0];

      if(!currentSource){
        Xms.Web.Alert(false, '当前类型已被禁用');
      }else {
        $("#resourcename").val(currentSource.modulename);
        $("#name").text(currentSource.modulelocalizedname);
        $tree.attr('data-url', ORG_SERVERURL + currentSource.resourceendpoint);
        $editform.prop('action', ORG_SERVERURL + currentSource.privilegestateendpoint);
        initTree();
      }
    });

    function searchTreeData(e) {
      var $tree_searcher = $('#tree_searcher'),
              val = $tree_searcher.val();
      $tree1.find('>ul>li.jqtree_common').hide();
      $tree1.find('>ul>li.jqtree_common').find('.jqtree-toggler-left').text('►');
      if (val != '') {
        $tree1.find('.jqtree-title').each(function () {
          var name = $(this).text();
          var $li = $(this).parents('li:first');
          if (name != '' && name.indexOf(val) != -1) {
            //  $li.show();
            //if ($li.parents('li:first').is(':hidden')) {
            $li.parents('li').show().find('.jqtree-toggler-left').text('▼');
            $li.parents('li').children('ul').show();
            //  }
            // $li.parents('li:first')
          } else {
            // $li.parents('li:first').find('.jqtree-toggler-left').addClass('jqtree-closed');
            //  $li.parents('li').show().find('.jqtree-toggler-left').text('►');
            //  $li.parents('li').hide()
            //  $li.hide();
          }
        });

      } else {
        $tree1.find('li.jqtree_common').show();
      }

    }
    var debound = $.deboundsEvent(100);
    $('#tree_searcher').on('change', function (e) {
      var self = this;
      //if (e.keyCode == '13') {
      debound(function () {
        searchTreeData.call(self, e)
      })
      // }
    }).next().on('click', function (e) {
      var self = this;
      debound(function () {
        searchTreeData.call(self, e)
      })
    })

  });

  var initTree_state = false;
  function initTree() {
    if(initTree_state) {
      $tree.tree('reload');
      return;
    }
    initTree_state = true;
    var treeDatas = [];
    $tree.tree({
      autoOpen: false
      , onTreeFinished: function (data, parent_node) {
        console.log(data, parent_node);
        var folder = $tree.find('.jqtree-folder');
        folder.each(function () {
          var $that = $(this);
          var list = $that.children('ul');
          var checkboxs = list.find('input[type="checkbox"]');
          var checkeds = list.find('input[type="checkbox"]:checked');
          if (checkboxs.length == checkeds.length) {
            $that.children('.jqtree-element').find('input[type="checkbox"]').prop('checked', true);
            $that.children('.jqtree-element').find('a').trigger('click');
          }
        });
      }
      , onCreateLi: function (node, $li) {
        $li.show();
        var isdisabled = '';
        if (node.id && node.id.indexOf('parentid') != -1) {
          isdisabled = 'disabled';
        }
        if (treeDatas.length != 1) {
          $li.find('.jqtree-title').before('<input type="checkbox" name="objectid" onclick="setState(this)"  value="' + node.id+ '" ' + (node.authorizationenabled ? 'checked' : '') + ' />&nbsp;&nbsp;');
        } else if (treeDatas.length == 1 && node.children && node.children.length==0) {
          $li.find('.jqtree-title').before('<span style="margin-left:10px;" /><input type="checkbox" '+isdisabled+' name="objectid" onclick="setState(this)" value="' + node.id + '" '+(node.authorizationenabled ? 'checked':'')+' />&nbsp;&nbsp;');
        }

      }
      , selectable: false,
      onCanSelectNode: function (node) {
        $tree.tree('openNode', node);
        return true;
      }
      , dataFilter: function (data) {
        var datas = Xms.Web.GetAjaxResult(data).content;
        console.log(datas)
        treeDatas = datas;
        handlerDatas(datas);
        return datas;
      }
    });
    var count = 0;
    function handlerDatas(datas) {

      $.each(datas, function (i, n) {
        if (!n.id) {
          n.id = 'parentid_' + Xms.Utility.Guid.NewGuid().ToString()
        }
        if (n.children && n.children.length > 0) {
          $.each(n.children, function (ii, nn) {
            nn._parentid = n.id;
          });
          handlerDatas(n.children);
        }
        //if (!n.children && count<1) {
        //    n.children = [{id:'234234234',label:'fdsfdsf'}];
        //    count++;
        //}
      });
    }
  }

  function getResourceInfo(callback){
    Xms.Web.GetJson(ORG_SERVERURL + "/api/security/resourceowners", null, function (data) {
      if (!data) return;
      console.log('data=', data);
      data = Xms.Web.GetAjaxResult(data);
      var result = data.content;
      var Items = function () {
        var self = this;
        result = $.grep(result, function (n, i) {
          n.modulelocalizedname = n.modulelocalizedname || '';
          return n.statecode == true && n.resourceendpoint;
        });
        self.lines = ko.observableArray(result);

        self.click = function (item) {
          $("#resourcename").val(item.modulename);
          $("#name").text(item.modulelocalizedname);
          $tree.data('url', ORG_SERVERURL + item.resourceendpoint);
          initTree();
          loadPrivilegeResources(item.resourceendpoint);
        }
      }
      var _item = new Items();
      console.log(_item);
      ko.applyBindings(_item);
      callback && callback(result);
    });
  }

  function loadPrivilegeResources(resourceEndpoint) {
    Xms.Web.GetJson(resourceEndpoint, null, function (data) {
      if (!data.IsSuccess) return;
      var result = data.content;
      console.info(result);

      if (result && result.length > 0) {
        $(result).each(function (i, n) {
          if (!n.id) {
            var treeid = Xms.Utility.Guid.EmptyGuid.ToString()
            n.id = treeid;
            n.isparent = true;
          }
          setLoadedChildrenSelected(n.objectid);
        });
      }
      else {
        var node = $tree.tree('getNodeById', Xms.Utility.Guid.EmptyGuid.ToString());
        if (node) {
          $tree.tree('openNode', node);
        }
      }
    });
  }
  function setChildrenSelected(nodeid) {
    var node = $tree.tree('getNodeById', nodeid);
    if (!node) return;
    $(node.element).find("input[type=checkbox][value=" + nodeid + "]").prop("checked", true);
    if (node) {
      $tree.tree('openNode', node);
    }
    for (var i = 0; i < node.children.length; i++) {
      var child = node.children[i];
      if (child.children.length > 0) {
        setChildrenSelected(child.id);
      }

      var childnode = $tree.tree('getNodeById', child.id);
      $(childnode.element).find("input[type=checkbox][value=" + child.id + "]").prop("checked", true);
      if (childnode) {
        $tree.tree('openNode', childnode);
      }

    }
  }
  function setLoadedChildrenSelected(nodeid) {
    var node = $tree.tree('getNodeById', nodeid);
    if (!node) return;
    $(node.element).find("input[type=checkbox][value=" + nodeid + "]").prop("checked", true);
    if (node) {
      $tree.tree('openNode', node);
    }
    if (node.children.length == 0) {
      var par_ele = $(node.element).parent().siblings(".jqtree-element");
      if (par_ele.length > 0) {
        var paridDom = par_ele.find("input[name='objectid']"), parid = paridDom.val();
        if (!paridDom.prop("checked")) {
          var parid_treeid = $tree.tree('getNodeById', parid)
          if (parid_treeid) {
            $tree.tree('openNode', parid_treeid);
          }
        }
      }
    }
  }

  function setState(t) {

    var flag = $(t).prop("checked");
    var nodeid = $(t).val();
    if (flag) {
      setChildrenSelected(nodeid);
    }
    else {
      var node = $tree.tree('getNodeById', nodeid);
      if (node.children.length > 0) {
        $(node.element).find("input[type=checkbox]").prop("checked", false);
      }
    }
  }
</script>

</body>
</html>